import { createRouter, createWebHashHistory } from 'vue-router'
import UserAuth from '@/utils/userAuth'
import Progress from '@/utils/progress'
import { SystemInfo } from '@/store/constant'
import baseRouter from '@/router/modules/baseRouter'
import adminRouter from '@/router/modules/adminRouter'
import homePage from '@/router/modules/homePage'

const homePath = '/home' // 首页路由

const routes = [
    {
        path: '/',
        meta: {
            name: '首页',
        },
        redirect: homePath,
    },
    homePage,
    ...baseRouter,
    adminRouter,
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: routes as any,
})

/**
 * 用户权限校验
 * @return {boolean}
 */
const isAuthenticated = () => {
    return !!UserAuth.getToken()
}

/** 路由白名单 */
const WhiteList = ['/login', '/40398', '/40399']

/**
 * 全局的前置守卫
 */
router.beforeEach(async (to, from, next) => {
    // 开启页面进度条
    Progress.start()

    // 检查用户是否已登录 // 判断是否需要是去登录界面，避免无限重定向
    if (!isAuthenticated() && to.path !== '/login') {
        if (WhiteList.includes(to.path)) {
            next()
        } else {
            // 将用户重定向到登录页面
            next({ path: '/login' })
        }
    } else {
        next()
    }
    document.title = to.meta.title ? `${to.meta.title}-${SystemInfo.NAME}` : SystemInfo.NAME
})

/**
 * 路由后置守卫
 */
router.afterEach(() => {
    // 结束页面进度条
    Progress.close()
})

export default router
